package org.springframework.prospring.ticket.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.prospring.ticket.dao.FieldDAO;
import org.springframework.prospring.ticket.domain.Field;
import org.springframework.prospring.ticket.domain.Turn;
import org.springframework.prospring.ticket.exception.BusinessException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;

import java.util.Set;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve User objects.
 *
 * @author Alexis Quiros
 */
public class FieldDAOHibernate extends HibernateDaoSupport implements FieldDAO {
    private static Log log = LogFactory.getLog(FieldDAOHibernate.class);

    public FieldDAOHibernate() {
        super();
        if (FieldDAOHibernate.log.isDebugEnabled()) {
            FieldDAOHibernate.log.debug("in FieldDAOHibernate Constructor");
        }
    }

    public Field findField(Long fieldId) {
        if (FieldDAOHibernate.log.isDebugEnabled()) {
            FieldDAOHibernate.log.debug("finding Field id: " + fieldId);
        }

        Field field = (Field)getHibernateTemplate().load(Field.class, fieldId);

        return field;
    }

    public Set<Turn> findTurns(Long fieldId) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /*
    public User findUser(Long id) {
        if (FieldDAOHibernate.log.isDebugEnabled()) {
            FieldDAOHibernate.log.debug("getting User id: " + id);
        }
        return (User) getHibernateTemplate().get(User.class, id);
    }
    */
    public void saveField(Field field) throws Exception {
        if (FieldDAOHibernate.log.isDebugEnabled()) {
            FieldDAOHibernate.log.debug("Saving Field: " + field);
        }

        if (StringUtils.isEmpty(field.getName())) {
            String message = "The name is required, name="+field.getName();
            FieldDAOHibernate.log.info(message);
            throw new BusinessException(message);
        }

        getHibernateTemplate().saveOrUpdate(field);

        if (FieldDAOHibernate.log.isDebugEnabled()) {
            FieldDAOHibernate.log.debug("fieldId set to: " + field.getId());
        }
    }

    public void removeField(Long fieldId) {
        if (FieldDAOHibernate.log.isDebugEnabled()) {
            FieldDAOHibernate.log.debug("removing Field id: " + fieldId);
        }

        Object field = getHibernateTemplate().load(Field.class, fieldId);
        getHibernateTemplate().delete(field);
    }


}
